﻿using System;
using System.Collections.Generic;
using System.IO;
using PSE.Deployment.SetupBase.Configuration;
using PSE.Deployment.SetupBase.Parameter;
using PSE.Deployment.Engine.CustomExceptions;
using PSE.Deployment.Engine.Interfaces;

namespace PSE.Deployment.SetupBase.Steps
{
    public class InstallMessageQueue : SetupStep<Configuration.Actions.InstallMessageQueue>
    {
        public InstallMessageQueue(IStepGroup parent, Group group, Configuration.Actions.InstallMessageQueue action, Parameter.Enums.SetupMode setupMode)
            : base(parent, group, action, setupMode)
        {
            this.ResetProgress(1);
        }

        public override void Execute()
        {
            this.ResetProgress(1);

            if (this.SetupMode == Parameter.Enums.SetupMode.Install)
            {
                InstallQueues();
            }
            else if (this.SetupMode == Parameter.Enums.SetupMode.Uninstall)
            {
                UninstallArtefacts();
            }
        }

        public override void Undo()
        {
            if (this.SetupMode == Parameter.Enums.SetupMode.Install)
            {
                UninstallArtefacts();
            }
        }

        private void InstallQueues()
        {
            foreach (Queue queue in Action.Queues)
            {
                if (this.IsStopped())
                    break;

                try
                {
                    this.IncrementProgress(queue.FullPath);

                    PSE.Deployment.Util.MSMQ.Create(queue.FullPath);

                    this.AddUsedBy(queue.FullPath);
                }
                catch
                {
                    this.DecrementProgress(queue.FullPath);
                    throw;
                }
            }
        }

        protected override void UninstallArtefact(string artefactName)
        {
            PSE.Deployment.Util.MSMQ.Delete(artefactName);
        }
    }
}
